<template>
  <div class="car">
    <img :src="`${host}${item.book.image}`" />
    <div class="info">
      <h3>{{ item.book.name }}</h3>
      <div>单价: {{ item.book.price }}</div>
      <n-input-number v-model:value="item.number" style="width: 80px" min="1" />
    </div>
    <n-button
      @click="removeACar(item._id)"
      class="mt-1"
      size="small"
      type="error"
      dashed
      >删除</n-button
    >
  </div>
</template>

<script lang="ts">
import { NButton, NInputNumber, useMessage } from "naive-ui";
import { defineComponent, PropType, ref, toRefs, watch, inject } from "vue";

import { Car } from "../interface/car.interface";
import { useCar } from "../hooks/UseCars";

export default defineComponent({
  name: "CarItem",
  props: { item: { type: Object as PropType<Car>, required: true } },
  components: { NButton, NInputNumber },
  setup(props) {
    const message = useMessage();
    const host = ref(import.meta.env.VITE_SEREVER_HOST as string);
    const { item } = toRefs(props);
    const { updateCar, deleteCar } = useCar();
    const flash = inject("flash") as Function;

    watch(
      () => item.value?.number,
      async (number) => {
        await updateCar(item.value?._id as string, number as number);
      }
    );

    const removeACar = async (id: string) => {
      const bool = await deleteCar(id);
      if (bool) {
        message.success("删除成功");
      } else {
        message.error("删除失败");
      }
      flash();
    };

    return {
      host,
      removeACar,
    };
  },
});
</script>

<style lang="scss">
.car {
  display: flex;

  img {
    max-width: 7rem;
  }

  .info {
    padding-left: 1rem;
    padding-right: 1rem;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    flex: 1;

    h3 {
      margin: 0;
    }
  }
}
</style>
